///
// * jdbm LICENSE v1.00
// *
// * Redistribution and use of this software and associated documentation
// * ("Software"), with or without modification, are permitted provided
// * that the following conditions are met:
// *
// * 1. Redistributions of source code must retain copyright
// *    statements and notices.  Redistributions must also contain a
// *    copy of this document.
// *
// * 2. Redistributions in binary form must reproduce the
// *    above copyright notice, this list of conditions and the
// *    following disclaimer in the documentation and/or other
// *    materials provided with the distribution.
// *
// * 3. The name "jdbm" must not be used to endorse or promote
// *    products derived from this Software without prior written
// *    permission of Cees de Groot.  For written permission,
// *    please contact cg@cdegroot.com.
// *
// * 4. Products derived from this Software may not be called "jdbm"
// *    nor may "jdbm" appear in their names without prior written
// *    permission of Cees de Groot.
// *
// * 5. Due credit should be given to the jdbm Project
// *    (http://jdbm.sourceforge.net/).
// *
// * THIS SOFTWARE IS PROVIDED BY THE ndbm PROJECT AND CONTRIBUTORS
// * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
// * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
// * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// * OF THE POSSIBILITY OF SUCH DAMAGE.
// *
// * Copyright 2001 (C) Alex Boisvert. All Rights Reserved.
// * Contributions are Copyright (C) 2001 by their associated contributors.
// *
// 

//*************************************************************************
//**  Included in JDMB 1.0 port to SharpDBM;  11/2013 Cyrus Neah cneah@codingreal.com
//**  SharpDBM is an independent reimplementation of the JDBM 1.0 software library in C#  
//*************************************************************************

using System;


using RecordManager = SharpDBM.RecordManager;
using RecordManagerFactory = SharpDBM.RecordManagerFactory;
using RecordManagerOptions = SharpDBM.RecordManagerOptions;

using BTree = SharpDBM.btree.BTree;

using LongComparator = SharpDBM.helper.LongComparator;
using Tuple = SharpDBM.helper.Tuple;
using TupleBrowser = SharpDBM.helper.TupleBrowser;
using System.Configuration;
using System.IO;

///
// * Example program dealing with B+Trees and Prime numbers.
// 
public class Primes
{

//    *
//     * Default number of prime number to populate in the database (if not specified on command-line)
//     
	public static int DEFAULT_POPULATE = 100;


//    *
//     * Default number of random lookups (if not specified on command-line)
//     
	public static int DEFAULT_LOOKUPS = 100;


//    *
//     * Record Manager used for persistence.
//     
	private RecordManager _recman;


//    *
//     * B+Tree holding prime numbers.
//     
	private BTree _primes;


//    *
//     * Random number generator.
//     
	private static Random _random = new Random();


//    *
//     * Main constructor
//     

	public Primes()
	{
		
	}


//    *
//     * Get the largest prime number in the database.
//     

//
	public virtual long getLargestPrime()
	 {
		Tuple tuple;
		TupleBrowser browser;
		long largest =0;

		tuple = new Tuple();
		browser = _primes.browse(null);
		if (browser.getPrevious(tuple))
		{
			largest = (long) tuple.Value;
			Console.WriteLine("Largest prime: " + largest);
		}
		else
		{
			Console.WriteLine("No prime number in the database.");
		}
		return largest;
	}


//    *
//     * Populate the database with more prime numbers.
//     *
//     * @param count Number of primes to add to database.
//     

//
	internal virtual void populate(int count)
	{
		long current;
		long largest;

		Console.WriteLine("Populating prime B+Tree...");

		// start after the largest known prime
		largest = getLargestPrime();
		

		current = largest + 1L;
		while (count > 0)
		{
			if (isPrime(current))
			{
				_primes.insert(current, current, false);
				Console.WriteLine("Found prime #" + _primes.size() + ": " + current);
				count--;
			}
			current = current + 1;
		}
		_recman.commit();
	}


//    *
//     * Returns true if a number is prime.
//     

//
	internal virtual bool isPrime(long number)
	{
		Tuple tuple;
		TupleBrowser browser;
		long largest=0L;
		long current;

		if (number <= 0L)
		{
			throw new ArgumentOutOfRangeException("Number must be greater than zero");
		}
		if (number == 1)
		{
			return true;
		}
		tuple = new Tuple();
		browser = _primes.browse();
		while (browser.getNext(tuple))
		{
			current = (long) tuple.Value;
			if (current != 1 && (number % current) == 0)
			{
				// not a prime because it is divisibe by a prime
				return false;
			}
		}
		// this is a prime
		return true;
	}


//    *
//     * Display a number of random prime numbers.
//     

//
	internal virtual void random(int count)
	{
		Tuple tuple;
		TupleBrowser browser;
		long largest;
		long number;

		tuple = new Tuple();
		largest = getLargestPrime();

		Console.WriteLine("Looking up " + count + " random primes....");
		long Start = System.DateTime.Now.Millisecond;
		for (int i=0; i<count; i++)
		{
			number = random(0, largest);
			browser = _primes.browse(number);
			if (browser.getNext(tuple))
			{
				number = (long) tuple.Value;
				Console.Write(number);
				Console.Write(", ");
			}
		}
		long Stop = System.DateTime.Now.Millisecond;
		Console.WriteLine();
		Console.WriteLine("Time: " + (Stop-Start)/count + " millis/lookup ");
	}


//    *
//     * Return true if number is a prime.
//     
	public static bool isPrimeCompute(long number)
	{
		for (int i=2; i<number/2; i++)
		{
			if ((number % i) == 0)
			{
				return false;
			}
		}
		return true;
	}


//    *
//     * Get random number between "low" and "high" (inclusively)
//     
	public static long random(long low, long high)
	{
		return ((long)(_random.NextDouble() * (high-low)) + low);
	}


//    *
//     * Static program entrypoint.
//     
	public virtual void execute()
	{
		
		int count;
		long number;
		long largest;

		
			
			long recid;


			// open database and setup an object cache
			//System.Configuration.ConfigurationManager.AppSettings["CACHE_SIZE"] = "10000";

			_recman = RecordManagerFactory.createRecordManager("primes");

			recid = _recman.getNamedObject("primes");

			if (recid == 0)
			{
				Console.WriteLine("Creating a new primes B+Tree.");
				_primes = BTree.createInstance(_recman, new LongComparator());
				_recman.setNamedObject("primes", _primes.getRecid());
			}
			else
			{
				_primes = BTree.load(_recman, recid);
				Console.WriteLine("B+Tree already contains " + _primes.size() + " primes.");
			}
			_recman.commit();

			
				
						count = DEFAULT_POPULATE;
					
					populate(count);
					
				
					
						number = (long)_random.NextDouble();
					
					largest = getLargestPrime();
					if (number > getLargestPrime())
					{
						throw new ArgumentOutOfRangeException("Number is larger than largest known prime in database.");
					}
					if (number != 0)
					{
						if (isPrime(number))
						{
							Console.WriteLine("The number " + number + " is a prime.");
						}
					}
					else
					{
						Console.WriteLine("The number " + number + " is not a prime.");
					}
					
				
					
						count = DEFAULT_LOOKUPS;
					
					random(count);
					
					Console.WriteLine("");
					Console.WriteLine("Actions:");
					Console.WriteLine("           -populate [number]   Populate database with prime numbers");
					Console.WriteLine("           -check [number]      Check if a number is a prime");
					Console.WriteLine("           -random [number]     Display random prime numbers");
					Console.WriteLine("");

					Console.WriteLine("Primes finished'");
                    _recman = null;

				}
			
			
				
			
		
	
}
